package com.haust.community.controller;

import com.haust.community.event.Event;
import com.haust.community.event.EventProducer;
import com.haust.community.pojo.Comment;
import com.haust.community.pojo.DiscussPost;
import com.haust.community.pojo.User;
import com.haust.community.service.CommentService;
import com.haust.community.service.DiscussPostService;
import com.haust.community.service.LikeService;
import com.haust.community.service.UserService;
import com.haust.community.utils.CommunityConstant;
import com.haust.community.utils.CommunityUtil;
import com.haust.community.utils.HostHolder;
import com.haust.community.utils.RedisKeyUtil;
import com.haust.community.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Auther: csp1999
 * @Date: 2020/11/25/13:40
 * @Description:
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增帖子操作
     *
     * @param title
     * @param content
     * @return
     */
    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJSONString(403, "你还没有登录哦!");
        }

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        discussPostService.addDiscussPost(post);

        // 发布帖子后，触发事件：将刚发布帖子的消息通知订阅的消费者
        // 消费者在消费帖子类型事件时，会将帖子信息 传递到 ES 服务器存储
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)// 主题: 发帖
                .setUserId(user.getId())// 当前用户id
                .setEntityType(ENTITY_TYPE_POST)// 实体类型帖子
                .setEntityId(post.getId());// 实体id 为帖子id
        eventProducer.fireEvent(event);

        // 获取帖子分数集合的key
        String redisPostScoreKey = RedisKeyUtil.getPostScoreKey();
        // 向 redisPostScoreKey 中存入帖子id
        redisTemplate.opsForSet().add(redisPostScoreKey,post.getId());

        // TODO 报错的情况,将来统一处理.
        return CommunityUtil.getJSONString(0, "发布成功!");
    }

    /**
     * 根据帖子id查询帖子详情
     *
     * @param discussPostId
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId")
                                         int discussPostId, Model model, Page page) {
        // 帖子
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("post", post);
        // 作者
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("user", user);

        // 从缓存中查询点赞有关的信息
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);

        // 点赞状态(即，当前用户是否对该帖子点过赞了)
        int likeStatus = hostHolder.getUser() == null ? 0 : // 如果用户没登录，则默认点赞状态是0，即未点赞
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        // 评论分页信息
        page.setLimit(5);
        page.setPath("/discuss/detail/" + discussPostId);
        page.setRows(post.getCommentCount());

        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.findCommentsByEntity(
                ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                // 评论VO
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                commentVo.put("user", userService.findUserById(comment.getUserId()));

                // 从缓存中查询点赞有关的信息
                // 评论点赞的数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);

                // 评论点赞的状态(即，当前用户是否对该帖子点过赞了)
                likeStatus = hostHolder.getUser() == null ? 0 : // 如果用户没登录，则默认点赞状态是0，即未点赞
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表
                List<Comment> replyList = commentService.findCommentsByEntity(
                        ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        replyVo.put("user", userService.findUserById(reply.getUserId()));
                        // 回复目标
                        User target = reply.getTargetId() == 0
                                ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        // 评论回复的点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 评论回复的点赞状态
                        likeStatus = hostHolder.getUser() == null ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);

                commentVoList.add(commentVo);
            }
        }

        model.addAttribute("comments", commentVoList);
        return "/site/discuss-detail";
    }

    /**
     * 帖子置顶操作
     *
     * @param id
     * @return
     */
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);

        // 触发发帖事件
        // 帖子帖子后，触发事件：将刚帖子帖子的消息通知订阅的消费者
        // 消费者在消费帖子类型事件时，会将帖子信息 传递到 ES 服务器存储/更新数据
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)// 主题: 发帖
                .setUserId(hostHolder.getUser().getId())// 登录用户id
                .setEntityType(ENTITY_TYPE_POST)// 实体类型: 帖子
                .setEntityId(id);// 实体id
        eventProducer.fireEvent(event);



        return CommunityUtil.getJSONString(0);
    }

    /**
     * 帖子加精操作
     *
     * @param id
     * @return
     */
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        // 加精帖子后，触发事件：将刚加精帖子的消息通知订阅的消费者
        // 消费者在消费帖子类型事件时，会将帖子信息 传递到 ES 服务器存储/更新数据
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)// 主题: 发帖
                .setUserId(hostHolder.getUser().getId())// 登录用户id
                .setEntityType(ENTITY_TYPE_POST)// 实体类型: 帖子
                .setEntityId(id);// 实体id
        eventProducer.fireEvent(event);

        // 获取帖子分数集合的key
        String redisPostScoreKey = RedisKeyUtil.getPostScoreKey();
        // 向 redisPostScoreKey 中存入帖子id
        redisTemplate.opsForSet().add(redisPostScoreKey,id);

        return CommunityUtil.getJSONString(0);
    }

    /**
     * 帖子删除操作
     *
     * @param id
     * @return
     */
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);

        // 触发删帖事件
        // 删除帖子后，触发事件：将刚删除帖子的消息通知订阅的消费者
        // 消费者在消费帖子类型事件时，会将帖子信息 传递到 ES 服务器存储/更新数据
        Event event = new Event()
                .setTopic(TOPIC_DELETE)// 主题: 删帖
                .setUserId(hostHolder.getUser().getId())// 登录用户id
                .setEntityType(ENTITY_TYPE_POST)// 实体类型: 帖子
                .setEntityId(id);// 实体id
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0);
    }
}
